package com.example.music.utils;

import android.util.Log;

import com.example.music.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import org.mozilla.universalchardet.UniversalDetector;


public class LyricParser {
    private Map<Integer, String> lyricMap = new LinkedHashMap<>(); // 使用LinkedHashMap保持插入顺序

    public void parse(InputStream inputStream1) throws IOException {
        // 1. 将整个流读入内存（避免流重置问题）
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream1.read(data)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        byte[] byteArray = buffer.toByteArray();

        // 2. 安全关闭原始流
        try {
            inputStream1.close();
        } catch (IOException e) {
            Log.w("LyricParse", "关闭原始流失败", e);
        }

        // 3. 检测编码
        UniversalDetector detector = new UniversalDetector(null);
        detector.handleData(byteArray, 0, byteArray.length);
        detector.dataEnd();

        String encoding = detector.getDetectedCharset();
        if (encoding == null) {
            // 优先尝试中文编码，再回退到UTF-8
            encoding = "GBK";
        }
        Log.d("EncodingDetect", "检测到编码: " + encoding);

        // 4. 创建基于内存的输入流（无需关闭）
        ByteArrayInputStream memoryStream = new ByteArrayInputStream(byteArray);
        PushbackInputStream pushbackStream = new PushbackInputStream(memoryStream, 3);
        BufferedReader reader = null;

        try {
            // 5. 处理BOM字符
            byte[] bom = new byte[3];
            int bytesReadBom = pushbackStream.read(bom);

            // 检查并跳过BOM
            if (bytesReadBom >= 3 &&
                    bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) {
                Log.d("BOM", "跳过UTF-8 BOM");
            } else if (bytesReadBom >= 2 &&
                    bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF) {
                Log.d("BOM", "跳过UTF-16 BE BOM");
            } else if (bytesReadBom >= 2 &&
                    bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {
                Log.d("BOM", "跳过UTF-16 LE BOM");
            } else {
                // 没有BOM，回退读取的字节
                if (bytesReadBom > 0) pushbackStream.unread(bom, 0, bytesReadBom);
            }

            // 6. 创建Reader
            reader = new BufferedReader(new InputStreamReader(pushbackStream, encoding));

            // 7. 解析内容
            String line;
            while ((line = reader.readLine()) != null) {
                // 处理文本级别的BOM（如\uFEFF）
                if (line.startsWith("\uFEFF")) {
                    line = line.substring(1);
                }
                parseLine(line);
            }
        } catch (Exception e) {
            Log.e("LyricParse", "解析过程中出错", e);
            throw new IOException("歌词解析失败: " + e.getMessage());
        } finally {
            // 8. 安全关闭Reader（内存流无需关闭）
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.w("LyricParse", "关闭reader失败", e);
                }
            }
        }

        Log.d("LyricParse", "成功解析 " + lyricMap.size() + " 行歌词");
    }

    private void parseLine(String line) {
        if (line.startsWith("[")) { // 确保行以 [ 开头
            int index = line.indexOf("]");
            if (index > 0 && line.length() > index + 1) {
                String timeStr = line.substring(1, index); // 获取时间字符串
                String lyric = line.substring(index + 1).trim(); // 获取歌词内容
                int time = parseTime(timeStr); // 解析时间
                if (time >= 0) { // 如果时间有效
                    lyricMap.put(time, lyric);
                }
            }
        }
    }

    private int parseTime(String timeStr) {
        try {
            String[] parts = timeStr.split(":");
            if (parts.length == 2||parts.length==3) {
                int minute = Integer.parseInt(parts[0]);
                float second = Float.parseFloat(parts[1]);
                return (int) (minute * 60 + second);
            }
        } catch (NumberFormatException e) {
            Log.e("LyricParser", "无法解析时间：" + timeStr);
        }
        return -1; // 解析失败返回-1
    }

    public Map<Integer, String> getLyricMap() {
        return lyricMap;
    }

    public String getAllLyrics() {
        StringBuilder allLyrics = new StringBuilder();
        for (String lyric : lyricMap.values()) {
            allLyrics.append(lyric).append("\n");
        }
        return allLyrics.toString();
    }
}